package com.wanpinghui.supplier.product.adapter;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.widgets.PlusMinuesView;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.product.bean.CartBean;
import com.wanpinghui.wphlibrary.model.product.bean.CartDataBean;
import com.wanpinghui.wphlibrary.model.product.bean.CartItemBean;
import com.wanpinghui.wphlibrary.model.product.bean.CartItemFormatBean;
import com.wanpinghui.wphlibrary.model.product.bean.OrderCreateParams;
import com.wanpinghui.wphlibrary.widgets.ThrottleButton;
import com.yunshl.yunshllibrary.recyclerview.BaseRecyclerViewAdapter;
import com.yunshl.yunshllibrary.utils.NumberUtil;

import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/12/22
 ***/

public class CartListAdapter extends BaseRecyclerViewAdapter {
    private List<CartDataBean> datas;
    private Map<String, View> viewMap = new HashMap<>();
    private SelectChangeListener selectChangeListener;
    private List<CartBean> cartBeans;
    private UserBean userBean;

    public void setSelectChangeListener(SelectChangeListener listener) {
        selectChangeListener = listener;
    }

    public double[] getCountTotal(int userId, int supperId) {
        double[] doubles = new double[]{0, 0, 0};
        if (cartBeans != null && cartBeans.size() > 0) {
            for (CartBean cartBean : cartBeans) {
                if (cartBean.getUser_id() == userId && cartBean.getSupplier_id() == supperId) {
                    if (cartBean.getItemList() != null && cartBean.getItemList().size() > 0) {
                        boolean isConsult = true;
                        for (CartItemBean cartItemBean : cartBean.getItemList()) {
                            if (cartItemBean.isSelected()) {
                                doubles[2] = doubles[2] + 1;
                                if (cartItemBean.getSpecItemList() != null && cartItemBean.getSpecItemList().size() > 0) {
                                    for (CartItemFormatBean formatBean : cartItemBean.getSpecItemList()) {
                                        doubles[0] = doubles[0] + formatBean.getQuantity();
                                        doubles[1] = doubles[1] + (formatBean.getPrice() * formatBean.getQuantity());
                                        if (formatBean.getQuantity() > 0 && !formatBean.isIs_consult()) {
                                            isConsult = false;
                                        }
                                    }
                                } else {
                                    doubles[0] = doubles[0] + cartItemBean.getQuantity();
                                    doubles[1] = doubles[1] + (cartItemBean.getPrice() * cartItemBean.getQuantity());
                                    if (!cartItemBean.isIs_consult()) {
                                        isConsult = false;
                                    }
                                }
                            }
                        }
                        if (isConsult) {
                            doubles[1] = -1;
                        }
                    }
                }
            }

        }
        return doubles;
    }

    /**
     * 生成订单创建参数
     *
     * @param userId
     * @param supperId
     * @return
     */
    public OrderCreateParams getParams(int userId, int supperId) {
        OrderCreateParams orderCreateParams;
        if (cartBeans != null && cartBeans.size() > 0) {
            for (CartBean cartBean : cartBeans) {
                if (cartBean.getUser_id() == userId && cartBean.getSupplier_id() == supperId) {
                    if (cartBean.getItemList() != null && cartBean.getItemList().size() > 0) {
                        for (CartItemBean cartItemBean : cartBean.getItemList()) {
                            if (cartItemBean.isSelected()) {
                                orderCreateParams = new OrderCreateParams(userId, supperId);
                                List<OrderCreateParams.ItemParams> itemParamsList = new ArrayList<>();
                                if (cartItemBean.getSpecItemList() != null && cartItemBean.getSpecItemList().size() > 0) {
                                    for (CartItemFormatBean formatBean : cartItemBean.getSpecItemList()) {
                                        if (formatBean.getQuantity() > 0) {
                                            OrderCreateParams.ItemParams itemParams = new OrderCreateParams.ItemParams(
                                                    formatBean.getId(), formatBean.getProduct_desc_id(), formatBean.getProduct_prices_id(), formatBean.getQuantity()
                                            );
                                            itemParamsList.add(itemParams);
                                        }
                                    }
                                } else if (cartItemBean.getQuantity() > 0) {
                                    OrderCreateParams.ItemParams itemParams = new OrderCreateParams.ItemParams(
                                            cartItemBean.getId(), cartItemBean.getProduct_desc_id(), null, cartItemBean.getQuantity()
                                    );
                                    itemParamsList.add(itemParams);
                                }
                                if (itemParamsList.size() > 0) {
                                    orderCreateParams.setItemList(itemParamsList);
                                    return orderCreateParams;
                                } else {
                                    return null;
                                }
                            }
                        }
                    }
                }
            }

        }
        return null;
    }

    public void setData(List<CartBean> cartList) {
        if (datas == null) {
            datas = new ArrayList<>();
        } else {
            datas.clear();
        }
        cartBeans = cartList;
        if (cartList != null && cartList.size() != 0) {
            for (int i = 0; i < cartList.size(); i++) {
                CartDataBean dataBean = new CartDataBean();
                dataBean.setType(1);
                dataBean.setCartBean(cartList.get(i));
                datas.add(dataBean);
                if (cartList.get(i).getItemList() != null && cartList.get(i).getItemList().size() > 0) {
                    for (int j = 0; j < cartList.get(i).getItemList().size(); j++) {
                        CartItemBean itemBean = cartList.get(i).getItemList().get(j);
                        if (itemBean.getSpecItemList() != null && itemBean.getSpecItemList().size() > 1) {
                            CartDataBean dataBean2 = new CartDataBean();
                            dataBean2.setType(3);
                            dataBean2.setCartItemBean(itemBean);
                            dataBean2.setCartBean(cartList.get(i));
                            if (j == cartList.get(i).getItemList().size() - 1) {
                                dataBean2.setHaveBottom(true);
                            }
                            datas.add(dataBean2);
                        } else {
                            CartDataBean dataBean3 = new CartDataBean();
                            dataBean3.setType(2);
                            dataBean3.setCartItemBean(itemBean);
                            if (j == cartList.get(i).getItemList().size() - 1) {
                                dataBean3.setHaveBottom(true);
                            }
                            dataBean3.setCartBean(cartList.get(i));
                            datas.add(dataBean3);
                        }

                    }
                }
            }
        }
        notifyDataSetChanged();
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        super.onBindViewHolder(holder, position);
        if (getItemViewType(position) == 1) {
            ((HeaderHolder) holder).textViewName.setText(datas.get(position).getCartBean().getSupplier_name());
        } else if (getItemViewType(position) == 2) {
            final OneFormatHoder formatHoder = (OneFormatHoder) holder;
            final CartItemBean itemBean = datas.get(position).getCartItemBean();
            formatHoder.textViewName.setText(itemBean.getName());
            formatHoder.textViewSecondName.setText(itemBean.getSecond_name());
            Glide.with(context).load(itemBean.getMain_img()).asBitmap().placeholder(R.mipmap.goods_bg_loading_a).error(R.mipmap.goods_bg_loading).into(formatHoder.imageViewMainImg);
            if (itemBean.getSpecItemList() != null && itemBean.getSpecItemList().size() > 0) {
                formatHoder.plusMinuesView.setCount(itemBean.getSpecItemList().get(0).getQuantity());
                if (itemBean.getSpecItemList().get(0).isIs_consult()) {
                    formatHoder.textViewPrice.setText("议价");
                } else {
                    formatHoder.textViewPrice.setText("￥" + NumberUtil.double2String(itemBean.getSpecItemList().get(0).getPrice()));
                }
            } else {
                formatHoder.plusMinuesView.setCount(itemBean.getQuantity());
                if (itemBean.isIs_consult()) {
                    formatHoder.textViewPrice.setText("议价");
                } else {
                    formatHoder.textViewPrice.setText("￥" + NumberUtil.double2String(itemBean.getPrice()));
                }
            }
            if (itemBean.isSelected()) {
                formatHoder.imageViewSelect.setSelected(true);
            } else {
                formatHoder.imageViewSelect.setSelected(false);
            }
            if (itemBean.getSpecItemList() != null && itemBean.getSpecItemList().size() > 0) {
                if (itemBean.getSpecItemList().get(0).getQuantity() < itemBean.getMin_quantity()) {
                    formatHoder.textViewTip.setVisibility(View.VISIBLE);
                } else {
                    formatHoder.textViewTip.setVisibility(View.GONE);
                }
            } else {
                if (itemBean.getQuantity() < itemBean.getMin_quantity()) {
                    formatHoder.textViewTip.setVisibility(View.VISIBLE);
                } else {
                    formatHoder.textViewTip.setVisibility(View.GONE);
                }
            }
            Glide.with(context).load(itemBean.getMain_img()).asBitmap().placeholder(R.mipmap.goods_bg_loading_a).error(R.mipmap.goods_bg_loading).into(formatHoder.imageViewMainImg);
            formatHoder.plusMinuesView.setOnCountChangeListener(new PlusMinuesView.OnCountChangeListener() {
                @Override
                public void onPlus() {
                }

                @Override
                public void onMinues() {
                }

                @Override
                public void onCountChange(int count) {
                    if (itemBean.getSpecItemList() != null && itemBean.getSpecItemList().size() > 0) {
                        itemBean.getSpecItemList().get(0).setQuantity(count);
                        if (selectChangeListener != null) {
                            selectChangeListener.onItemCountChange(itemBean.getSpecItemList().get(0).getId(), count);
                        }
                    } else {
                        itemBean.setQuantity(count);
                        if (selectChangeListener != null) {
                            selectChangeListener.onItemCountChange(itemBean.getId(), count);
                        }
                    }
                    if (count < itemBean.getMin_quantity()) {
                        formatHoder.textViewTip.setVisibility(View.VISIBLE);
                    } else {
                        formatHoder.textViewTip.setVisibility(View.GONE);
                    }
                    //notifyDataSetChanged();
                }
            });
            formatHoder.linearLayoutCartArea.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (itemBean.isSelected()) {
                        itemBean.setSelected(false);
                    } else {
                        itemBean.setSelected(true);
                    }
                    if (itemBean.isSelected()) {
                        formatHoder.imageViewSelect.setSelected(true);
                    } else {
                        formatHoder.imageViewSelect.setSelected(false);
                    }
                    notifyDataSetChanged();
                }
            });
            if (datas.get(position).isHaveBottom()) {
                formatHoder.relativeLayoutBottom.setVisibility(View.VISIBLE);
                formatHoder.textViewBuyer.setText("采购人：" + datas.get(position).getCartBean().getUser_name());
                double[] priceCount = getCountTotal(datas.get(position).getCartBean().getUser_id(), datas.get(position).getCartBean().getSupplier_id());
                formatHoder.textViewProductCount.setText(Integer.toString((int) priceCount[0]));
                if (priceCount[1] == -1) {
                    formatHoder.textViewProductTotal.setText("议价");
                } else {
                    formatHoder.textViewProductTotal.setText("￥" + NumberUtil.double2StringAdaptive(priceCount[1]));
                }
                if (datas.get(position).getCartBean().getUser_id() == Integer.parseInt(userBean.getUser().getId())) {
                    String text = "立即采购";
                    if (priceCount[2] > 0) {
                        text = "立即采购(" + ((int) priceCount[2]) + ")";
                    }
                    formatHoder.buttonBuy.setText(text);
                    formatHoder.buttonBuy.setOnThrottleClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (selectChangeListener != null) {
                                selectChangeListener.onBuy(getParams(datas.get(position).getCartBean().getUser_id(), datas.get(position).getCartBean().getSupplier_id()));
                            }
                        }
                    });
                } else {
                    String text = "代他采购";
                    if (priceCount[2] > 0) {
                        text = "代他采购(" + ((int) priceCount[2]) + ")";
                    }
                    formatHoder.buttonBuy.setText(text);
                    formatHoder.buttonBuy.setOnThrottleClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (selectChangeListener != null) {
                                selectChangeListener.onBuy(getParams(datas.get(position).getCartBean().getUser_id(), datas.get(position).getCartBean().getSupplier_id()));
                            }
                        }
                    });

                }
            } else {
                formatHoder.relativeLayoutBottom.setVisibility(View.GONE);
            }
        } else {
            final MoreFromatHolder formatHoder = (MoreFromatHolder) holder;
            final CartItemBean productBean = datas.get(position).getCartItemBean();
            formatHoder.textViewName.setText(productBean.getName());
            final CartFormatAdapter formatAdapter = new CartFormatAdapter(context);
            formatHoder.listViewFormats.setAdapter(formatAdapter);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) formatHoder.listViewFormats.getLayoutParams();
            layoutParams.height = DensityUtil.dip2px(54 * productBean.getSpecItemList().size() + productBean.getSpecItemList().size() - 1);
            formatHoder.listViewFormats.setLayoutParams(layoutParams);
            formatAdapter.setDatas(productBean.getSpecItemList());
            formatHoder.textViewSecondName.setText(productBean.getSecond_name());
            Glide.with(context).load(productBean.getMain_img()).asBitmap().placeholder(R.mipmap.goods_bg_loading_a).error(R.mipmap.goods_bg_loading).into(formatHoder.imageViewMainImg);
            if (productBean.isSelected()) {
                formatHoder.imageViewSelect.setSelected(true);
            } else {
                formatHoder.imageViewSelect.setSelected(false);
            }
            if (productBean.getAllFormatQuantity() < productBean.getMin_quantity()) {
                formatHoder.textViewTip2.setVisibility(View.VISIBLE);
            } else {
                formatHoder.textViewTip2.setVisibility(View.GONE);
            }
            //105 +57 第一个提示显示距顶部104dp，以后每个加57dp
            formatAdapter.setOnCountChangeListener(new CartFormatAdapter.OnCountChangeListener() {
                @Override
                public void onChange(int pos, CartItemFormatBean formatBean) {
//                    if (productBean.getAllFormatQuantity() <= productBean.getMin_quantity()) {
//                        formatHoder.textViewTip2.setVisibility(View.VISIBLE);
//                    }else {
//                        formatHoder.textViewTip2.setVisibility(View.GONE);
//                    }
                    if (selectChangeListener != null) {
                        selectChangeListener.onItemCountChange(formatBean.getId(), formatBean.getQuantity());
                    }
                    notifyDataSetChanged();
                }
            });

            formatHoder.linearLayoutItemArea.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (productBean.isSelected()) {
                        productBean.setSelected(false);
                    } else {
                        productBean.setSelected(true);
                    }
                    if (productBean.isSelected()) {
                        formatHoder.imageViewSelect.setSelected(true);
                    } else {
                        formatHoder.imageViewSelect.setSelected(false);
                    }
                    notifyDataSetChanged();
                }
            });
            if (datas.get(position).isHaveBottom()) {
                formatHoder.relativeLayoutBottom.setVisibility(View.VISIBLE);
                formatHoder.textViewBuyer.setText("采购人：" + datas.get(position).getCartBean().getUser_name());
                double[] priceCount = getCountTotal(datas.get(position).getCartBean().getUser_id(), datas.get(position).getCartBean().getSupplier_id());
                formatHoder.textViewProductCount.setText(Integer.toString((int) priceCount[0]));
                if (priceCount[1] == -1) {
                    formatHoder.textViewProductTotal.setText("议价");
                } else {
                    formatHoder.textViewProductTotal.setText("￥" + NumberUtil.double2StringAdaptive(priceCount[1]));
                }
                if (datas.get(position).getCartBean().getUser_id() == Integer.parseInt(userBean.getUser().getId())) {
                    String text = "立即采购";
                    if (priceCount[2] > 0) {
                        text = "立即采购(" + ((int) priceCount[2]) + ")";
                    }
                    formatHoder.buttonBuy.setText(text);
                    formatHoder.buttonBuy.setOnThrottleClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (selectChangeListener != null) {
                                selectChangeListener.onBuy(getParams(datas.get(position).getCartBean().getUser_id(), datas.get(position).getCartBean().getSupplier_id()));
                            }
                        }
                    });
                } else {
                    String text = "代他采购";
                    if (priceCount[2] > 0) {
                        text = "代他采购(" + ((int) priceCount[2]) + ")";
                    }
                    formatHoder.buttonBuy.setText(text);
                    formatHoder.buttonBuy.setOnThrottleClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (selectChangeListener != null) {
                                selectChangeListener.onBuy(getParams(datas.get(position).getCartBean().getUser_id(), datas.get(position).getCartBean().getSupplier_id()));
                            }
                        }
                    });
                }
            } else {
                formatHoder.relativeLayoutBottom.setVisibility(View.GONE);
            }
        }
    }

//    /**
//     * 显示不得低于起订数量提示方案
//     * @param pos
//     * @param key
//     * @param layoutParent
//     */
//    private void showNotEnoughTip(int pos, String key, FrameLayout layoutParent) {
//        if (!viewMap.containsKey(key)) {
//            TextView textView = new TextView(context);
//            textView.setPadding(DensityUtil.dip2px(5), DensityUtil.dip2px(2), DensityUtil.dip2px(5), DensityUtil.dip2px(8));
//            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
//            textView.setBackgroundResource(R.mipmap.goods_bg_tips);
//            textView.setTextColor(ContextCompat.getColor(context, R.color.white));
//            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( DensityUtil.dip2px(131), DensityUtil.dip2px(35));
//            layoutParams.topMargin = DensityUtil.dip2px(105 + (pos * 57));
//            layoutParams.rightMargin = DensityUtil.dip2px(19);
//            layoutParams.gravity = Gravity.RIGHT;
//            //layoutParams.rightMargin = DensityUtil.dip2px(105+(pos*57));
//            textView.setText("不得低于起订数量");
//            layoutParent.addView(textView, layoutParams);
//            viewMap.put(key, textView);
//        }
//    }


    public CartListAdapter(Context context) {
        super(context);
        userBean = WPHSdk.getService(OAuthService.class).getUserInfo(null);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == 1) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_cart_header, null);
            return new HeaderHolder(view);
        } else if (viewType == 2) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_cart_single_format, null);
            OneFormatHoder hoder = new OneFormatHoder(view);
            hoder.setIsRecyclable(false);
            return hoder;
        } else {
            View view = LayoutInflater.from(context).inflate(R.layout.item_cart_muitiple_format, null);
            MoreFromatHolder moreFromatHolder = new MoreFromatHolder(view);
            moreFromatHolder.setIsRecyclable(false);
            return moreFromatHolder;
        }
    }

    @Override
    public int getItemCount() {
        return datas == null ? 0 : datas.size();
    }

    @Override
    public int getItemViewType(int position) {
        return datas.get(position).getType();
    }

    class HeaderHolder extends RecyclerView.ViewHolder {
        TextView textViewName;

        public HeaderHolder(View itemView) {
            super(itemView);
            textViewName = (TextView) itemView.findViewById(R.id.tv_name);
        }
    }

    class OneFormatHoder extends RecyclerView.ViewHolder {
        ImageView imageViewSelect;
        ImageView imageViewMainImg;
        TextView textViewName;
        TextView textViewSecondName;
        TextView textViewPrice;
        PlusMinuesView plusMinuesView;
        TextView textViewTip;
        LinearLayout linearLayoutCartArea;
        RelativeLayout relativeLayoutBottom;
        TextView textViewBuyer;
        TextView textViewProductCount;
        TextView textViewProductTotal;
        ThrottleButton buttonBuy;

        public OneFormatHoder(View itemView) {
            super(itemView);
            imageViewSelect = (ImageView) itemView.findViewById(R.id.iv_select);
            imageViewMainImg = (ImageView) itemView.findViewById(R.id.iv_image);
            textViewName = (TextView) itemView.findViewById(R.id.tv_name);
            textViewSecondName = (TextView) itemView.findViewById(R.id.tv_second_name);
            textViewPrice = (TextView) itemView.findViewById(R.id.tv_price);
            plusMinuesView = (PlusMinuesView) itemView.findViewById(R.id.view_plus_minues);
            textViewTip = (TextView) itemView.findViewById(R.id.tv_least_count_tip_2);
            linearLayoutCartArea = (LinearLayout) itemView.findViewById(R.id.ll_item_area);
            relativeLayoutBottom = (RelativeLayout) itemView.findViewById(R.id.rl_bottom_area);
            textViewBuyer = (TextView) itemView.findViewById(R.id.tv_buyer);
            textViewProductCount = (TextView) itemView.findViewById(R.id.tv_product_count);
            textViewProductTotal = (TextView) itemView.findViewById(R.id.tv_product_total);
            buttonBuy = (ThrottleButton) itemView.findViewById(R.id.btn_buy);
        }
    }

    class MoreFromatHolder extends RecyclerView.ViewHolder {
        ImageView imageViewSelect;
        ImageView imageViewMainImg;
        TextView textViewName;
        TextView textViewSecondName;
        ListView listViewFormats;
        FrameLayout layoutArea;
        LinearLayout linearLayoutItemArea;
        RelativeLayout relativeLayoutBottom;
        TextView textViewBuyer;
        TextView textViewProductCount;
        TextView textViewProductTotal;
        ThrottleButton buttonBuy;
        TextView textViewTip2;

        public MoreFromatHolder(View itemView) {
            super(itemView);
            imageViewSelect = (ImageView) itemView.findViewById(R.id.iv_select);
            imageViewMainImg = (ImageView) itemView.findViewById(R.id.iv_image);
            textViewName = (TextView) itemView.findViewById(R.id.tv_name);
            textViewSecondName = (TextView) itemView.findViewById(R.id.tv_second_name);
            listViewFormats = (ListView) itemView.findViewById(R.id.lv_formats);
            layoutArea = (FrameLayout) itemView.findViewById(R.id.fl_area);
            linearLayoutItemArea = (LinearLayout) itemView.findViewById(R.id.linearlayout);
            relativeLayoutBottom = (RelativeLayout) itemView.findViewById(R.id.rl_bottom_area);
            textViewBuyer = (TextView) itemView.findViewById(R.id.tv_buyer);
            textViewProductCount = (TextView) itemView.findViewById(R.id.tv_product_count);
            textViewProductTotal = (TextView) itemView.findViewById(R.id.tv_product_total);
            buttonBuy = (ThrottleButton) itemView.findViewById(R.id.btn_buy);
            textViewTip2 = (TextView) itemView.findViewById(R.id.tv_least_count_tip);
            itemView.setLayoutParams(new GridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        }
    }

    public interface SelectChangeListener {
        void onBuy(OrderCreateParams params);

        void onItemCountChange(int id, int count);
    }


}
